package com.ruoyi.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.domain.*;
import com.ruoyi.mapper.ErpSupplierManagementMapper;
import com.ruoyi.service.impl.ErpPurchaseRequestManagementServiceImpl;
import com.ruoyi.service.impl.ErpSupplierManagementServiceImpl;
import com.ruoyi.service.impl.PurchaseDetailBomImpl;
import io.jsonwebtoken.lang.Strings;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.service.IErpPurchaseRequestManagementService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 请购单管理Controller
 * 
 * @author ruoyi
 * @date 2025-07-17
 */
@RestController
@RequestMapping("/purchase/purchase")
public class ErpPurchaseRequestManagementController extends BaseController {
    @Autowired
    private IErpPurchaseRequestManagementService erpPurchaseRequestManagementService;
    @Autowired
     private PurchaseDetailBomImpl purchaseDetailBom;
    @Autowired
    private ErpSupplierManagementServiceImpl supplierManagementService;
    @Autowired
    private ErpSupplierManagementServiceImpl erpSupplierManagementServiceImpl;

    /**
     * 查询请购单管理列表
     */
    @PreAuthorize("@ss.hasPermi('purchase:purchase:list')")
    @GetMapping("/list")
    public TableDataInfo list(ErpPurchaseRequestManagement erpPurchaseRequestManagement) {
        startPage();
        List<ErpPurchaseRequestManagement> list = erpPurchaseRequestManagementService.selectErpPurchaseRequestManagementList(erpPurchaseRequestManagement);
        return getDataTable(list);
    }

    /**
     * 导出请购单管理列表
     */
    @PreAuthorize("@ss.hasPermi('purchase:purchase:export')")
    @Log(title = "请购单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ErpPurchaseRequestManagement erpPurchaseRequestManagement) {
        List<ErpPurchaseRequestManagement> list = erpPurchaseRequestManagementService.selectErpPurchaseRequestManagementList(erpPurchaseRequestManagement);
        ExcelUtil<ErpPurchaseRequestManagement> util = new ExcelUtil<ErpPurchaseRequestManagement>(ErpPurchaseRequestManagement.class);
        util.exportExcel(response, list, "请购单管理数据");
    }

    /**
     * 获取请购单管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('purchase:purchase:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(erpPurchaseRequestManagementService.selectErpPurchaseRequestManagementById(id));
    }

    /**
     * 新增请购单管理
     */
//    @PreAuthorize("@ss.hasPermi('purchase:purchase:add')")
    @Log(title = "请购单管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public Map<String, Object> add( @RequestBody PurchaseRequest request) {
        ErpPurchaseRequestManagement erpPurchaseRequestManagement = request.getErpPurchaseRequestManagement();
        List<PurchaseDetailBom> purchaseRequestItemList = request.getPurchaseRequestItemList();
        System.err.println("erpPurchaseRequestManagement = " + erpPurchaseRequestManagement);
        Map map = erpPurchaseRequestManagementService.insertErpPurchaseRequestManagement(erpPurchaseRequestManagement);
        Integer purchaseId = erpPurchaseRequestManagement.getXzid();
        System.err.println("purchaseId = " + purchaseId);
        this.addmaterials(purchaseRequestItemList,purchaseId);
        return map;
    }

    /**
     * 修改请购单管理
     */
    @PreAuthorize("@ss.hasPermi('purchase:purchase:edit')")
    @Log(title = "请购单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ErpPurchaseRequestManagement erpPurchaseRequestManagement) {
        return toAjax(erpPurchaseRequestManagementService.updateErpPurchaseRequestManagement(erpPurchaseRequestManagement));
    }

    /**
     * 删除请购单管理
     */
    @PreAuthorize("@ss.hasPermi('purchase:purchase:remove')")
    @Log(title = "请购单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(erpPurchaseRequestManagementService.deleteErpPurchaseRequestManagementByIds(ids));
    }


    /*审核供应商管理 审核*/
    @PostMapping("/audit")
    public AjaxResult updateaudit(@RequestParam("id") int id , @RequestParam("opinion") String  opinion, @RequestParam("choice") int choice) {
        ErpPurchaseRequestManagement erpSupplierManagement = new ErpPurchaseRequestManagement();
        erpSupplierManagement.setOpinion(opinion);
        erpSupplierManagement.setChoice(choice);
        erpSupplierManagement.setId(id);
        Map<String, Integer> i = erpPurchaseRequestManagementService.updateAudit(erpSupplierManagement);
        //添加审批记录

        if (i.get("提交成功？") > 0) {
            return AjaxResult.success(i);
        } else {
            return AjaxResult.error("审核失败");
        }
    }


    /*审核供应商管理 审核提交*/
    @PostMapping("/submit/{id}")
    public AjaxResult submit(@PathVariable("id") int id) {
        Map<String, Integer> i = erpPurchaseRequestManagementService.submit(id);
        if (i.get("提交成功？") > 0) {
            return AjaxResult.success(i);
        } else {
            return AjaxResult.error("提交失败");

        }
    }




/*强制终止*/
    @PostMapping("/end")
    public  Map<String, String>forceCompleteProcess(@RequestParam("ids") List<Integer> ids ,@RequestParam("reasona") String reasona) {
        Map<String, String> end = erpPurchaseRequestManagementService.end(ids, reasona);
        return end;
    }


    /*审核供应商管理 弃审*/
    @PostMapping("/reject/{id}")
    public AjaxResult rejectaudit( @PathVariable("id") int id) {
        int i = erpPurchaseRequestManagementService.rejectaudit( id);
        if (i > 0) {
            return AjaxResult.success("驳回成功");
        } else {
            return AjaxResult.error("驳回失败");
        }
    }


    /*请购管理 保存*/
    @PostMapping("/saveUpdateaudit")
    public AjaxResult saveAudit(@RequestBody ErpPurchaseRequestManagement erpPurchaseRequestManagement) {
        System.out.println(erpPurchaseRequestManagement);
        if (ObjectUtils.isEmpty(erpPurchaseRequestManagement)) {
            System.out.println("发送过来对象为空");
        }


        System.out.println("开始保存");
        boolean save = erpPurchaseRequestManagementService.save(erpPurchaseRequestManagement);
        if (save) {
            return AjaxResult.success("保存成功");
        }
        return AjaxResult.error("保存失败");
    }


    /*审核供应商管理 关联待采购 细目表*/
    @PostMapping("/purchasedetail/{id}")
    public List<PurchaseDetailBom> PurchaseDetail(@PathVariable("id") int id) {
       List< PurchaseDetailBom> purchaseDetail = erpPurchaseRequestManagementService.PurchaseDetail(id);
        Optional<List<PurchaseDetailBom>> optionalStr = Optional.ofNullable(purchaseDetail);
        if (optionalStr.isEmpty()) { // Java 11
            System.err.println("查询失败");
            System.err.println("purchaseDetail = " + purchaseDetail);
        }else {
            System.out.println("查询成功");
        }
        return purchaseDetail;



    }



    /* 查看详细物料 发送过来的id为采购细目表中联合物料表的id*/
    @PostMapping("/detail/{id}")
    public List<PurchaseDetailBom> selectPurchaseDetailid(@PathVariable("id") int id) {
        List< PurchaseDetailBom> purchaseDetail = erpPurchaseRequestManagementService.PurchaseDetailId(id);
        Optional<List<PurchaseDetailBom>> optionalStr = Optional.ofNullable(purchaseDetail);
        if (optionalStr.isEmpty()) { // Java 11
            System.err.println("查询失败");
            System.err.println("purchaseDetail = " + purchaseDetail);
        }else {
            System.out.println("查询成功");
        }
        return purchaseDetail;



    }












/*
* 查询可选择物料*/
    @GetMapping("/selectmaterials")
    public List<PurchaseDetailBom> selectmaterials() {
       List<PurchaseDetailBom>  materials = erpPurchaseRequestManagementService.selectmaterials();
        Optional<List<PurchaseDetailBom>> optionalStr = Optional.ofNullable(materials);
        if (optionalStr.isEmpty()) { // Java 11
            System.err.println("查询失败");
            System.err.println("purchaseDetail = " + materials);
        }else {
            System.out.println("查询成功");
            System.err.println("purchaseDetail = " + materials);
        }
        return materials;



    }

//     * 新增可选择物料 发送主键和他的物料id 加入到中间表中*/
    @PostMapping("/addmaterials")
    public Map<String,Integer> addmaterials(@RequestParam("ids") List<PurchaseDetailBom> ids,@RequestParam("key") int Key) {
       boolean materials = purchaseDetailBom.addmaterials(ids, Key);
 Map <String,Integer> map=new HashMap<>();
        if (materials) { // Java 11
            System.err.println("新增成功");
            System.err.println("purchaseDetail = " + materials);
            map.put("msg",200);

        }else {
            System.out.println("新增失败");
            map.put("msg",0);
        }
        return map;



    }

    //查看审核的记录
    @GetMapping("/jilu/{id}")
    public List<ApprovalRecord> approvalrecord(@PathVariable("id") Integer id) {
        System.err.println("id = " + id);
        List<ApprovalRecord> purchaseDetail = erpPurchaseRequestManagementService.jilu(id);
        Optional<List<ApprovalRecord>> optionalStr = Optional.ofNullable(purchaseDetail);
        if (optionalStr.isEmpty()) { // Java 11
            System.err.println("查询失败");
            System.err.println("purchaseDetail = " + purchaseDetail);
        }else {
            System.out.println("查询成功");
            System.err.println("purchaseDetail = " + purchaseDetail);
        }
            return purchaseDetail;



    }


    /*
     * 删除可选择物料*/
    @PostMapping("/deletematerials/{id}/{wid}")
    public int deletematerials(@PathVariable("id") int id ,@PathVariable("wid") int wid) {
       int  materials = erpPurchaseRequestManagementService.deleteDetailId(id,wid);
        if (materials!=0) { // Java 11
            System.err.println("删除成功");
            return materials;
        }else {
            System.out.println("删除失败");
            return materials;
        }




    }
//类只是容器不是内容的 里面装入内容才叫对象 只有对象才有内容
    @GetMapping("/selectsupper")
    public List<ErpSupplierManagement> selectsupper() {
        List<ErpSupplierManagement>  erpSupplierManagements = erpSupplierManagementServiceImpl.getsupper();
        Optional<List<ErpSupplierManagement>> optionalStr = Optional.ofNullable(erpSupplierManagements);
        if (optionalStr.isEmpty()) { // Java 11
            System.err.println("查询失败");
            System.err.println("erpSupplierManagements = " + erpSupplierManagements);
        }else {
            System.out.println("查询成功");
            System.err.println("purchaseDetail = " + erpSupplierManagements);
        }
        return erpSupplierManagements;



    }
    @PostMapping(value = "/{id}")
    public AjaxResult orderwuliaoId(@PathVariable("id") int id) {
        return success(purchaseDetailBom.orderwuliaoId(id));
    }




    @Log(title = "请购单管理", businessType = BusinessType.INSERT)
    @PostMapping("/updatesw")
    public int updatesw(@RequestBody PurchaseRequest2 request) {
        ErpPurchaseRequestManagement erpPurchaseRequestManagement = request.getErpPurchaseRequestManagement();
        System.err.println("erpPurchaseOrderRequestManagement = " + erpPurchaseRequestManagement);
        List<PurchaseDetailBom2> purchaseRequestItemList = request.getPurchaseRequestItemList();
        System.err.println("erpPurchaseRequestManagement = " + erpPurchaseRequestManagement);
        int updatesw= erpPurchaseRequestManagementService.updatesw(erpPurchaseRequestManagement);
        Integer purchaseId = erpPurchaseRequestManagement.getId();
        System.err.println("purchaseId = " + purchaseId);
        System.err.println("purchaseId = " + purchaseId);
   purchaseDetailBom.addmaterials2(purchaseRequestItemList, purchaseId);
        return updatesw;
    }
}





























